﻿//获取s3客户端实例
const s3Client = new S3Client({
    endpoint: 'http://api.oss.boadan.com',
    s3ForcePathStyle: true,
    signatureVersion: 'v4',
    region: 'us-east-1',
    forcePathStyle: true,
    credentials: {
        accessKeyId: 'Ma8zc6ibeMeYYkMas9zu',
        secretAccessKey: 'JfVpUfcR7M0m9o5FiiYNnv20V9J8qjDDrMrZeonn'
    }
})

// 文件选择变化时触发的函数
const triggerFileInput = () => {
    fileInput.value.click();
};

// 分片
const createChunks = (File: File, partSize = 5 * 1024 * 1024): Blob[] => {
    const chunks: Blob[] = [];
    let offset = 0;
    while (offset < File.size) {
        const end = Math.min(offset + partSize, File.size);
        chunks.push(File.slice(offset, end));
        offset += partSize;
    }
    return chunks;
};

// 隐藏输入框
const handleFileChange = (e: any) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
        file.value = selectedFile;
        chunks.value = createChunks(selectedFile);
    }
    wname.value = selectedFile?.name;
    console.log(selectedFile);
};
const startUpload = async () => {
    if (!file.value) {
        uploadMessage.value = '请先选择文件';
        return;
    }

    isUploading.value = true;
    uploadMessage.value = '上传中，请稍候...';
    const bucket = 'chenjiale';
    const key = `uploads/${file.value.name}`;
    const partSize = 5 * 1024 * 1024;  // 分片大小5MB
    const localStorageKey = `upload_${key}`;  // 用于缓存上传进度

    // 获取本地缓存的上传状态
    const uploadState = JSON.parse(localStorage.getItem(localStorageKey) || '{}');
    const uploadedChunks = uploadState.uploadedChunks || [];  // 已上传的分片
    const etags = uploadState.etags || [];  // 已上传分片的ETag

    // 计算已上传的文件大小
    let totalUploaded = uploadedChunks.reduce((acc, partNumber) => {
        const chunk = chunks.value[partNumber - 1]; // 获取已上传的分片
        return acc + chunk.size;
    }, 0);

    // 计算上传进度并保留两位小数
    progress.value = parseFloat(((totalUploaded / file.value.size) * 100).toFixed(2));

    try {
        // 如果没有UploadId，先创建Multipart上传任务
        let uploadId = uploadState.uploadId;
        if (!uploadId) {
            const params = {
                Bucket: bucket,
                Key: key,
                ContentType: file.value.type
            };
            const data = await s3Client.send(new CreateMultipartUploadCommand(params));
            uploadId = data.UploadId;  // 获取并保存上传ID

            // 存储上传任务状态
            localStorage.setItem(localStorageKey, JSON.stringify({
                uploadId,
                uploadedChunks,
                etags
            }));
        }

        // 从已上传的分片继续上传
        for (let i = uploadedChunks.length; i < chunks.value.length; i++) {
            const partNumber = i + 1;
            const chunk = chunks.value[i];

            // 上传分片
            const response = await s3Client.send(new UploadPartCommand({
                Bucket: bucket,
                Key: key,
                UploadId: uploadId,
                PartNumber: partNumber,
                Body: chunk
            }));

            console.log(response);
            console.log(response.ETag);

            // 更新ETag和已上传的部分
            etags.push(response.ETag);
            uploadedChunks.push(partNumber);

            // 更新本地缓存
            localStorage.setItem(localStorageKey, JSON.stringify({
                uploadId,
                uploadedChunks,
                etags
            }));

            // 更新上传进度，并保留两位小数
            totalUploaded += chunk.size;
            progress.value = parseFloat(((totalUploaded / file.value.size) * 100).toFixed(2));
        }

        // 上传完成，合并分片
        await s3Client.send(new CompleteMultipartUploadCommand({
            Bucket: bucket,
            Key: key,
            UploadId: uploadId,
            MultipartUpload: {
                Parts: uploadedChunks.map((partNumber, index) => ({
                    ETag: etags[index],
                    PartNumber: partNumber
                }))
            }
        }));

        fileUrl.value = `http://api.oss.boadan.com/${bucket}/${key}`;
        uploadMessage.value = '文件上传成功';

        // 上传完成后清除本地缓存
        localStorage.removeItem(localStorageKey);
    } catch (error) {
        uploadMessage.value = '文件上传失败';
        console.error(error);
    } finally {
        isUploading.value = false;
    }
};


//响应式变量
const fileInput = ref(null);
const file = ref(null);
const chunks = ref([]);
const progress = ref(0);
const wname = ref(null);
const uploadMessage = ref('');
const isUploading = ref(false);
const fileUrl = ref('');




